package com.test.qpbgboot.base.exception;

import com.test.qpbgboot.base.response.JsonResult;
import com.test.qpbgboot.base.response.ResultStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.Objects;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException exception) {
        String message = exception.getMessage();
        log.error("IllegalArgumentException: {}", message);
        return new JsonResult(ResultStatus.ILLEGAL_ARGUMENT, message);
    }

    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException exception) {
        String message = exception.getMessage();
        log.error("RuntimeException: {}", message);
        return JsonResult.failure(message);
    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        String message = Objects.requireNonNull(exception.getBindingResult().getFieldError()).getDefaultMessage();
        log.error("MethodArgumentNotValidException: {}", message);
        return new JsonResult(ResultStatus.INCORRECT_FORMAT, message);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException exception) {
        String message = exception.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException: {}", message);
        return new JsonResult(ResultStatus.INCORRECT_FORMAT, message);
    }

    @ExceptionHandler
    public JsonResult doHandleServiceException(ServiceException exception) {
        log.error("ServiceException: {}", exception.getMsg());
        if (exception.getDetail() != null) {
            return new JsonResult(exception.getCode(), exception.getMsg(), exception.getDetail());
        } else {
            return new JsonResult(exception.getCode(), exception.getMsg());
        }
    }
}
